import { ECSEntity } from "../../../3rd/ECS/ECSEntity";
import { ECSSystem } from "../../../3rd/ECS/ECSSystem";
import { BindNode } from "../../../Bridge/BindNode";
import { MathBirde } from "../../../Bridge/Math";
import NodeHelper from "../../../Bridge/NodeHelper";
import { Vector3 } from "../../../Bridge/Vec";
import { App } from "../../../Framework/Core/App";
import Util from "../../../Framework/Util/Util";
import { GameRT } from "../../GameRT";
import { BarrierComponent } from "../components/NoDataComponent";
import { PositionComponent } from "../components/PositionComponent";
import { RenderNodeComponent } from "../components/RenderNodeComponent";
import { BackStartPoint } from "../events/GameEvent";

export class BarrierFactorySystem extends ECSSystem {

    private readonly barrierRoot:BindNode;
    
    constructor()
    {
        super();
        this.barrierRoot = NodeHelper.FindBindNode("barrierRoot")
    }

    start(): void {
        this.removeBarriers();
        this.bornBarriers();    
    }
    bornBarriers()
    {
        var num = Math.floor( MathBirde.RandRange(0,GameRT.ScenLength/4));

        // Util.Log("添加",num,"障碍物")
        for (let index = 0; index < num; index++) 
        {
            var barrierEty = new ECSEntity("barrier"+index);
            var barrier =  App.Instance.poolMgr.Get("barrier");
            barrierEty.addComponent(new RenderNodeComponent(barrier));
            barrierEty.addComponent(new BarrierComponent());
            var leftOrRight = GameRT.RoadSpace * Math.ceil( MathBirde.RandRange(-1,1) );
            var randomPos = new Vector3(leftOrRight,0,MathBirde.RandRange(0,GameRT.ScenLength));
            barrierEty.addComponent(new PositionComponent(randomPos)); 
            this.ecs.entities.add(barrierEty);           
        }
    }
    removeBarriers()
    {
        var barrierComs =  this.ecs.components.all(BarrierComponent)
    
        var removeIds:string[]=[];
        barrierComs.forEach(element => {  
            removeIds.push(element.entityId);
        });

        removeIds.forEach(entityId=>{
            var enity = this.ecs.entities.get(entityId);
            var goWarp = enity.getComponent(RenderNodeComponent).node
            goWarp.Put(); //回收节点对象
            // Util.Log("回收",barrierComs.length,"障碍物")
            this.ecs.entities.delete(enity)
        })
        
    }

    update()
    {
        var backPoint = this.ecs.events.fetch(BackStartPoint)
        backPoint.forEach(element => 
        {
            this.removeBarriers();
            this.bornBarriers();    
        });
    }
}